package com.launch.carmanager.common.utils;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.launch.carmanager.BuildConfig;
import com.launch.carmanager.data.CommonIntercept;

import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 * Created by ganquan on 2019/3/28 09:51
 */
public class RetrofitWrapper {
    private RetrofitWrapper() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    private static volatile Retrofit SINGLETON;
    //请求的网址，
    private static volatile String ENDPOINT = BuildConfig.API_ENDPOINT;

    public static <T> T createApi(Class<T> clazz) {
        if (SINGLETON == null) {
            synchronized (RetrofitWrapper.class) {
                if (SINGLETON == null) {
                    SINGLETON = getRetrofit();
                }
            }
        }
        return SINGLETON.create(clazz);
    }

    private static Retrofit getRetrofit() {
        Retrofit.Builder rfAPIBuilder = new Retrofit.Builder();
        rfAPIBuilder.baseUrl(ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

        OkHttpClient.Builder okClientBuilder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool())
                .retryOnConnectionFailure(false);

        if (BuildConfig.DEBUG) {
            //网络请求拦截器，用于拦截网络请求，调试接口
            okClientBuilder.addNetworkInterceptor(new StethoInterceptor());
        }
//        okClientBuilder.addInterceptor(new CommonIntercept());
        rfAPIBuilder.client(okClientBuilder.build());

        return rfAPIBuilder.build();
    }

    public static void resetEndpoint(String endpoint) {
        synchronized (RetrofitWrapper.class) {
            ENDPOINT = endpoint;
            SINGLETON = getRetrofit();
        }
    }

    public static String getEndpoint() {
        return ENDPOINT;
    }
}
